home *** CD-ROM | disk | FTP | other *** search
- Path: news.umbc.edu!not-for-mail
- From: schlein@umbc.edu (Jonas J. Schlein)
- Newsgroups: comp.lang.c
- Subject: Re: Simple Program Question
- Date: 29 Feb 1996 18:17:03 -0500
- Organization: University of Maryland Baltimore County
- Message-ID: <4h5c5f$fhb@umbc9.umbc.edu>
- References: <4gsr9u$sk6@newsbf02.news.aol.com>
- NNTP-Posting-Host: umbc9.umbc.edu
- NNTP-Posting-User: schlein
-
- Tycope <tycope@aol.com> wrote:
- |> I am trying to write a non -interactive program that calculates all
- |> integer triples (i, j, k) such that
- |> 0 < i < j < k < l and i + j + k = l. Print out the number of triples that
- |> satisfy the requirements and print out every millionth triple. Can anyone
- |> see where I am missing the boat in the following code. The program runs
- |> and immediately terminates. Thanks in advance for any feedback.
- |>
- |> #include <stdio.h>
- |>
- |> long int i, j, k, l;
- |> long int count;
-
- Ok we can assume all these are 0 since they are declared global.
-
- |> int
- |> main (void)
- |> {
- |> do
- |> {
- |> (l = i + j + k);
-
- This is zero the first time through the loop and 9 (2+3+4) every time after
- that.
-
- |> (i = 1);
- |> (j = 2);
- |> (k = 3);
-
- These values are set EVERY iteration.
-
- |> (i++, j++, k++);
-
- That makes your new triple (2,3,4), but not for long...See above.
-
- |> (++count);
- |> if (count % 1000000 == 0)
-
- Personally I'd use some extra ()'s there.
-
- |> {
- |> printf("%ld(i) + %ld(j) + %ld(k) = %ld(l)", i, j, k, l);
-
- Either make a newline or stick in an explicit fflush() or you may be
- sitting around for output.
-
- |> }
- |>
- |> } while (0 < i < j < k < l);
-
- Now this is flat out wrong. C boolean operators are not mathematics
- inequalities so you must explicitly say what you want. In this case:
-
- while ((0 < i) && (i < j) && (j < k) && (k < l));
-
- |>
- |> return (0);
- |> }
-
- Here's some fixed code using a for loop to compute the same:
-
- #include <stdio.h>
-
- int main (void)
- {
- long int i, j, k, l;
- long int count;
-
- for (i = 1, j = i + 1, k = j + 1, l = i + j + k, count = 0;
- (0 < i) && (i < j) && (j < k) && (k < l);
- i++, j++, k++, count++, l = i + j + k)
- if ((count % 1000000) == 0)
- printf ("%ld(i) + %ld(j) + %ld(k) = %ld(l)\n", i, j, k, l);
-
- return (0);
- }
-
- Note that eventually something is going to overflow so there should be
- an extra terminating condition based on the number of iterations you
- want to perform (MAXIMUM) in your program. The above code should serve
- as only a suggestion on a possible way to begin.
- --
- "If it wasn't for C, we would be using BASI, PASAL, and OBOL."
-
- Jonas J. Schlein (schlein@gl.umbc.edu)
-